import path from 'path';

import fse from 'fs-extra';

import { getJson5Obj } from '../../../../src/utils/json-util.js';
import { runHvigorAsync, setDefaultStrictMode } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { Project } from '../../plugins/project-builder/models/project-models';
import { ICaseRecord } from '../../plugins/report-builder/report-models';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibrary]: 1,
  },
};
/**
 *  1. hvigor-config设置sourceMap生成路径
 *  2. 构建har包
 *  3. 构建之后检查mapping文件夹和sourceMaps.map是否存在于指定路径
 */
const testFun: TestCaseFun = async (project: Project, taskConfig: TestTaskOption, record: ICaseRecord) => {
  const projectRoot = project.projectRootPath();
  setDefaultStrictMode(projectRoot);
  // 指定生成sourceMap的父文件夹
  const outputSourceMapPath = path.resolve(projectRoot, 'test111');

  const rootPath = project.projectRootPath();
  const hvigorConfigPath = path.resolve(rootPath, 'hvigor', 'hvigor-config.json5');
  const hvigorConfigObj = getJson5Obj(hvigorConfigPath);

  // hvigor-config增加配置，添加sourceMap的路径
  hvigorConfigObj.properties = {
    'ohos.arkCompile.sourceMapDir': outputSourceMapPath,
  };
  fse.writeFileSync(hvigorConfigPath, JSON.stringify(hvigorConfigObj));

  // 构建har包
  const command = ['assembleHar'];
  await runHvigorAsync(project.projectRootPath(), command);

  // 解析路径下是否存在指定文件sourceMap
  const moduleName = project.getModule('staticLibrary').name;
  expect(fse.existsSync(path.resolve(outputSourceMapPath, moduleName, 'sourceMaps.map'))).toBe(true);
};

TestCaseBuilder.builder()
  .caseName('DTS2024111812135')
  // eslint-disable-next-line max-len
  .description('配置"ohos.arkCompile.sourceMapDir": 指定目录下生成字节码har的mapping产物')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testFun)
  .load();
